package com.irate.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.adapter.FriendListAdapter;
import com.irate.cache.ImageCache.ImageCacheParams;
import com.irate.cache.ImageFetcher;
import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.User;
import com.irate.provider.ContentManager;

public class FriendViewFriend extends Fragment {

	protected static final String TAG = FriendFragment.class.getName();

	protected ImageFetcher imageFetcher;
	protected static final String IMAGE_CACHE_DIR = "thumbs";
	protected int mImageThumbSize = 150;
	protected ListView friendList;
	protected FriendListAdapter adapter;
	protected Handler handler;
	protected ProgressDialog dialog;
	protected EditText textSearch;
	protected ImageView butSearch;
	// protected Timer myTimer;
	// protected AutoRefresh autoRefresh;
	protected UserDAO userDao;

	protected updateUI fragmentParent;

	public interface updateUI {
		public void onUpdate(int i);
	}

	public FriendViewFriend() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.friend_view_friend, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
		execute();
	}

	@Override
	public void onResume() {
		super.onResume();
		imageFetcher.setExitTasksEarly(false);

		// myTimer = new Timer();
		// autoRefresh = new AutoRefresh(resfresh);
		// myTimer.scheduleAtFixedRate(autoRefresh, ContentManager.getInstance()
		// .getRefreshTime(), ContentManager.getInstance()
		// .getRefreshTime());
	}

	@Override
	public void onPause() {
		super.onPause();

		// myTimer.cancel();

		imageFetcher.setPauseWork(false);
		imageFetcher.setExitTasksEarly(true);
		imageFetcher.flushCache();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		imageFetcher.closeCache();
	}

	private void init() {

		handler = new Handler();
		userDao = new UserDAO();

		ImageCacheParams cacheParams = new ImageCacheParams(getActivity(),
				IMAGE_CACHE_DIR);

		cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of
		imageFetcher = new ImageFetcher(getActivity(), mImageThumbSize);
		imageFetcher.setLoadingImage(R.drawable.user);
		imageFetcher.addImageCache(
				((FragmentActivity) getActivity()).getSupportFragmentManager(),
				cacheParams);
		textSearch = (EditText) getActivity().findViewById(R.id.textSearch);
		butSearch = (ImageView) getActivity().findViewById(R.id.butSearch);

		friendList = (ListView) getActivity().findViewById(R.id.list_friend);

	}

	private void execute() {

		try {
			fragmentParent = (updateUI) ContentManager.getInstance().getFrienFragment();
		} catch (Exception e) {

		}

		butSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (textSearch.getText().toString().trim().equals("")) {
					Toast.makeText(getActivity(), "Input not fault",
							Toast.LENGTH_LONG).show();
				} else {
					String keyw = textSearch.getText().toString().trim()
							.toLowerCase(Locale.getDefault());
					List<User> listResult = new ArrayList<User>();
					for (User user : ContentManager.getInstance()
							.getListFriend()) {
						if (user.getFirst_name()
								.toLowerCase(Locale.getDefault())
								.contains(keyw)
								|| user.getLast_name()
										.toLowerCase(Locale.getDefault())
										.contains(keyw)) {
							listResult.add(user);
						}
					}

					fillDataToListView(listResult);
				}
			}
		});

		textSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					if (textSearch.getText().toString().trim().equals("")) {
						Toast.makeText(getActivity(), "Input not fault",
								Toast.LENGTH_LONG).show();
					} else {
						String keyw = textSearch.getText().toString().trim()
								.toLowerCase(Locale.getDefault());
						List<User> listResult = new ArrayList<User>();
						for (User user : ContentManager.getInstance()
								.getListFriend()) {
							if (user.getFirst_name()
									.toLowerCase(Locale.getDefault())
									.contains(keyw)
									|| user.getLast_name()
											.toLowerCase(Locale.getDefault())
											.contains(keyw)) {
								listResult.add(user);
							}
						}

						fillDataToListView(listResult);
					}
					return true;
				}

				return false;
			}
		});

		// if (ContentManager.getInstance().getListFriend().size() > 0) {
		// fillDataToListView();
		// } else {
		if (ContentManager.getInstance().isLogin()) {
			dialog = ProgressDialog.show(getActivity(), getResources()
					.getString(R.string.friend),
					getResources().getString(R.string.loading), true);
			userDao.getFriendList(handlerListFriend, getActivity(), dialog);
		}
		// }

	}

	private synchronized void fillDataToListView(List<User> values) {
		adapter = new FriendListAdapter(values, imageFetcher, getActivity(),
				handlerRemoveFriend);

		friendList.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		friendList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
					imageFetcher.setPauseWork(true);
				} else {
					imageFetcher.setPauseWork(false);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
	}

	protected synchronized void fillDataToListView() {
		List<User> values = new ArrayList<User>(ContentManager.getInstance()
				.getListFriend());

		adapter = new FriendListAdapter(values, imageFetcher, getActivity(),
				handlerRemoveFriend);
		friendList.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		friendList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
					imageFetcher.setPauseWork(true);
				} else {
					imageFetcher.setPauseWork(false);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});

	}

	AsyncHttpResponseHandler handlerRemoveFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			Toast.makeText(
					getActivity(),
					getResources().getString(
							R.string.remove_friend_request_success),
					Toast.LENGTH_LONG).show();

			int n = ContentManager.getInstance().getNumOfFriend();
			fragmentParent.onUpdate(n - 1);
			ContentManager.getInstance().setNumOfFriend(n - 1);
			
			//fillDataToListView();
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();
			} catch (Exception ex) {

			}
		}
	};

	// Runnable resfresh = new Runnable() {
	//
	// @Override
	// public void run() {
	// if (ContentManager.getInstance().isLogin()) {
	// try {
	// if (getActivity() != null && userDao != null
	// && handlerListFriend != null) {
	// userDao.getFriendList(handlerListFriend, getActivity(),
	// null);
	// }
	// } catch (Exception e) {
	// }
	// }
	// }
	// };

	AsyncHttpResponseHandler handlerListFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			List<User> lst = userDao.parseListData(new String(response));

			fragmentParent.onUpdate(lst.size());
			ContentManager.getInstance().setListFriend(lst);
			ContentManager.getInstance().setNumOfFriend(lst.size());
			fillDataToListView();
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");

			fragmentParent.onUpdate(0);

		}
	};

}
